package com.baijiayun.liveuibase.ascamera

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AlertDialog
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import com.baijia.bjydialog.DialogAction
import com.baijia.bjydialog.MaterialDialog
import com.baijiayun.livecore.LiveSDK
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.context.LPError
import com.baijiayun.livecore.context.LiveRoom
import com.baijiayun.livecore.utils.CommonUtils
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.livecore.wrapper.LPRecorder
import com.baijiayun.liveuibase.LiveCameraWithUI
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.base.BaseScreenActivity
import com.baijiayun.liveuibase.base.getViewModel
import com.baijiayun.liveuibase.error.ErrorFragment
import com.baijiayun.liveuibase.error.ErrorViewModel
import com.baijiayun.liveuibase.loading.LoadingWindow
import com.baijiayun.liveuibase.loading.OnLoadingCompleteListener
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.getParentViewGroup
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.uibase_activity_ascamera.*
import java.util.concurrent.TimeUnit
import kotlin.random.Random

/**
 * Created by pengwenjian on 2020/11/13
 * Describe:
 */
class AsCameraActivity : BaseScreenActivity(), AsCameraListener {
    private val REQUEST_CODE_PERMISSION_CAMERA = 1

    //30s 不触摸视频自动隐藏 触摸则显示
    private val AUTO_HIDE_TIME = 30L
    private var noTouchTime = 0
    private var showMenu = true
    private var loadingWindow: LoadingWindow? = null
    private var showTechSupport = false
    private var isReconnect = false
    private var liveRoom: LiveRoom? = null
    private var disposes: CompositeDisposable? = null
    private var disposeOfAutoHide: Disposable? = null
    private var mobileNetworkDialogShown = false
    private var url: String? = null
    private var menuDialog: Dialog? = null
    private var enterRoomSuccess = false

    private val errorFragment by lazy {
        ErrorFragment()
    }

    private var recorder: LPRecorder? = null

    companion object {
        var roomExitListener: LiveCameraWithUI.LPRoomExitListener? = null
        var enterRoomConflictListener: LiveCameraWithUI.RoomEnterConflictListener? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        initFullScreen()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 5.0+ 打开硬件加速
            window.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        savedInstanceState?.remove("android:support:fragments")
        setTheme(R.style.BJYBaseLiveTheme)
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        initRoomData(savedInstanceState, intent)
        changeLayoutParams()
        hideSysUIComponent()
        initEvent()
        enterRoom()
    }

    override fun isDefaultOrientation() = false
    private fun initFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    private fun hideSysUIComponent() {
        supportActionBar?.hide()
    }

    private fun changeLayoutParams() {
        val layoutParams = videoContainer.layoutParams as ConstraintLayout.LayoutParams
        val menuParams = menuContainer.layoutParams
        if (DisplayUtils.isAspectRatioLarge(this)) {
            layoutParams.dimensionRatio = "W,16:9"
        } else{
            layoutParams.dimensionRatio = "H,16:9"
        }
        val view = if (DisplayUtils.isPad(this)) {
            menuParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            menuParams.height = resources.getDimensionPixelSize(R.dimen.bjy_base_ascamera_icon_container_size)
            View.inflate(this, R.layout.uibase_layout_ascamera_menu_h, null)
        }else {
            menuParams.width = resources.getDimensionPixelSize(R.dimen.bjy_base_ascamera_icon_container_size)
            menuParams.height = ViewGroup.LayoutParams.MATCH_PARENT
            View.inflate(this, R.layout.uibase_layout_ascamera_menu_v, null)
        }
        menuContainer.addView(view, menuParams)
        view.findViewById<View>(R.id.ivSwitchCamera).setOnClickListener {
            recorder?.switchCamera()
        }
        view.findViewById<View>(R.id.ivClose).setOnClickListener {
            finish()
        }
        view.findViewById<View>(R.id.tvMenu).setOnClickListener {
            showDefinitionMenu()
        }
    }

    private fun showDefinitionMenu() {
        val items = ArrayList<String>()
        when (recorder?.maxVideoDefinition ?: LPConstants.LPResolutionType.LOW) {
            LPConstants.LPResolutionType._360 -> {
                items.add(getString(R.string.base_live_definition_low))
                items.add(getString(R.string.base_live_definition_360p))
            }
            LPConstants.LPResolutionType.HIGH -> {
                items.add(getString(R.string.base_live_definition_low))
                items.add(getString(R.string.base_live_definition_360p))
                items.add(getString(R.string.base_live_definition_high))
            }
            LPConstants.LPResolutionType._720, LPConstants.LPResolutionType._1080 -> {
                items.add(getString(R.string.base_live_definition_low))
                items.add(getString(R.string.base_live_definition_360p))
                items.add(getString(R.string.base_live_definition_high))
                items.add(getString(R.string.base_live_definition_720p))
            }
            else -> {
                items.add(getString(R.string.base_live_definition_low))
            }
        }
        if (liveRoom?.roomType == LPConstants.LPRoomType.Multi) {
            items.remove(getString(R.string.base_live_definition_360p))
        }
        if (items.isEmpty() || items.size == 1) {
            return
        }
        menuDialog = MaterialDialog.Builder(this)
                .itemsColorRes(R.color.base_theme_live_product)
                .items(items)
                .itemsCallback { dialog, _, _, text ->
                    run {
                        val error = when (text) {
                            getString(R.string.base_live_definition_360p) -> {
                                recorder?.setCaptureVideoDefinition(LPConstants.LPResolutionType._360)
                            }
                            getString(R.string.base_live_definition_high) -> {
                                recorder?.setCaptureVideoDefinition(LPConstants.LPResolutionType.HIGH)
                            }
                            getString(R.string.base_live_definition_720p) -> {
                                recorder?.setCaptureVideoDefinition(LPConstants.LPResolutionType._720)
                            }
                            else -> recorder?.setCaptureVideoDefinition(LPConstants.LPResolutionType.LOW)
                        }
                        if (error == null) {
                            setDefinitionText(recorder?.videoDefinition)
                        }
                        dialog.dismiss()
                    }
                }
                .build()
        menuDialog?.show()
    }

    private fun initRoomData(savedInstanceState: Bundle?, intent: Intent) {
        url = if (savedInstanceState == null) {
            intent.getStringExtra("url")
        } else {
            savedInstanceState.getString("url")
        }
    }

    private var isBackstage = false
    private var attachVideoOnResume = false

    override fun onResume() {
        super.onResume()
        isBackstage = false
        if (attachVideoOnResume) {
            attachLocalVideo()
        }
        if (enterRoomSuccess) {
            liveRoom?.onlineUserVM?.updateMediaState()
        }
    }

    override fun onStop() {
        super.onStop()
        isBackstage = true
        if (isFinishing) {
            return
        }
        if (enterRoomSuccess) {
            liveRoom?.onlineUserVM?.updateMediaState()
        }
        attachVideoOnResume = recorder?.isVideoAttached == true
        if (recorder?.isPublishing == true) {
            recorder?.stopPublishing()
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString("url", url)
    }

    override fun getLayoutId() = R.layout.uibase_activity_ascamera

    private fun enterRoom(liveRoom: LiveRoom? = null) {
        loadingWindow = LoadingWindow(this, false)
        loadingWindow!!.run {
            showLoading()
            /**
             *  设备状态检测，检测成功则开始做加入直播间粗啊哦做
             */
            this.checkDevice(object : LoadingWindow.EnterRoomListener {
                override fun onEnterRoom() {
                    this@AsCameraActivity.liveRoom = enterRoom(liveRoom, url, object : OnLoadingCompleteListener {
                        override fun onLoadingSteps(step: Int, totalSteps: Int) {
                            // do nothing
                        }

                        override fun onLoadingComplete(liveRoom: LiveRoom) {
                            hideLoading(view)
                            enterRoomSuccess()
                        }

                        override fun onLoadingError(error: LPError?) {
                            hideLoading(view)
                            showError(error)
                        }
                    })
                    initLiveRoom()
                }
            })
        }
    }

    private fun showLoading() {
        loadingContainer.removeAllViews()
        loadingContainer.addView(loadingWindow?.view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    }

    private fun hideLoading(view: View?) {
        val parentView = getParentViewGroup(view)
        parentView?.removeView(view)
    }

    private fun enterRoomSuccess() {
        liveRoom?.run {
            recorder = getRecorder()
            if (!isClassStarted) {
                finish()
                return
            }
            setDefinitionText(recorder?.videoDefinition)
            subscribe(this)
            enterRoomSuccess = true
        }
    }

    private fun setDefinitionText(definition: LPConstants.LPResolutionType?) {
        findViewById<TextView>(R.id.tvMenu).text = when (definition?.typeValue) {
            1 -> getString(R.string.base_live_definition_high)
            2 -> getString(R.string.base_live_definition_720p)
            4 -> getString(R.string.base_live_definition_360p)
            else -> getString(R.string.base_live_definition_low)
        }
    }

    private fun showErrorDlg(it: LPError?) {
        val errorCode = it?.code?.toInt()
        val errorModel = getViewModel { ErrorViewModel() }
        when (errorCode) {
            LPError.CODE_ERROR_LOGIN_UNIQUE_CONFLICT -> {
                errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_CONFILICT)
            }
            LPError.CODE_ERROR_NEW_SMALL_COURSE, LPError.CODE_ERROR_MAX_STUDENT, LPError.CODE_ERROR_ENTER_ROOM_FORBIDDEN -> {
                errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_REENTER , getString(R.string.base_live_override_error), getString(R.string.base_live_enter_room))
            }
            LPError.CODE_ERROR_HOST_UNKNOW -> {
                errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_RECONNECT, getString(R.string.base_live_host_unknow), getString(R.string.base_live_enter_room))
            }
            LPError.CODE_ERROR_CLASS_END_KICK_OUT_TIPS, LPError.CODE_ERROR_CLASS_EXPIRED -> {
                errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_FINISH,  it.message, getString(R.string.base_live_i_know))
            }
            LPError.CODE_ERROR_NETWORK_FAILURE->{
                errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_RECONNECT,  getString(R.string.base_live_reconnect_tip), getString(R.string.base_live_retry))
            }
            else -> errorModel.init(ErrorFragment.ErrorType.ERROR_HANDLE_RECONNECT,  getString(R.string.base_live_reconnect_tip), getString(R.string.base_live_retry))
        }
        replaceFragment(errorContainer.id, errorFragment)
    }

    private fun showKickOutDlg(error: LPError) {
        release()
        val builder = AlertDialog.Builder(this)
        val dialog = builder.setMessage(error.message)
                .setPositiveButton(R.string.base_live_confirm) { dialog1, _ ->
                    dialog1.dismiss()
                    this.finish()
                }.create()
        dialog.setCancelable(false)
        if (!isFinishing) {
            dialog.show()
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(this, R.color.base_theme_live_product))
        }
    }

    private fun subscribe(liveRoom: LiveRoom) {
        disposes = CompositeDisposable()
        disposes?.run {
            addAll(
                    liveRoom.observableOfKickOut.observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                showError(it)
                            },
                    liveRoom.observableOfClassSwitch.delay(Random.nextInt(2) + 1L, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                finish()
                            },
                    liveRoom.observableOfClassEnd.observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                showToastMessage(R.string.base_live_class_end_le)
                                finish()
                            },
                    liveRoom.observableOfLoginConflict.observeOn(AndroidSchedulers.mainThread())
                            .subscribe { iLoginConflictModel ->
                                release()
                                if (enterRoomConflictListener != null) {
                                    enterRoomConflictListener!!.onConflict(this@AsCameraActivity, iLoginConflictModel.conflictEndType, object : LiveCameraWithUI.LPRoomExitCallback {
                                        override fun exit() {
                                            finish()
                                        }

                                        override fun cancel() {
                                            finish()
                                        }

                                    })
                                } else {
                                    finish()
                                }
                            },
                    liveRoom.speakQueueVM.observableOfStopAsCamera.observeOn(AndroidSchedulers.mainThread())
                            .subscribe { finish() },
                    //老师开关自己摄像头实际是来控制外接设备的状态
                    liveRoom.speakQueueVM.observableOfMediaControl.observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                if (isBackstage) {
                                    attachVideoOnResume = it.isVideoOn
                                } else {
                                    val recorder = liveRoom.getRecorder<LPRecorder>()
                                    if (it.isVideoOn) {
                                        if (!recorder.isVideoAttached) {
                                            attachLocalVideo()
                                        }
                                    } else {
                                        if (recorder.isVideoAttached) {
                                            detechLocalVideo()
                                        }
                                    }
                                }
                            },
                    liveRoom.speakQueueVM.observableOfActiveUsers
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                //进教室自动打开视频
                                if (liveRoom.speakQueueVM.enableAsCamera()) {
                                    attachLocalVideo()
                                } else {
                                    showStopAsCamera()
                                }
                            },

                    liveRoom.onlineUserVM.observableOfUserOut
                            .filter { TextUtils.equals(liveRoom.speakQueueVM.replacedUser?.userId,it.userId) }
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                //用户退出外接设备也退出
                                finish()
                            },
                    liveRoom.speakQueueVM.observableOfPresenterChange
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                //主讲人不在
                                if (TextUtils.isEmpty(it)) {
                                    showStopAsCamera()
                                } else if (liveRoom.speakQueueVM.replacedUser != null
                                        && liveRoom.speakQueueVM.replacedUser.userId != it
                                        && !liveRoom.speakQueueVM.isPresenterUser(liveRoom.speakQueueVM.replacedUser)) {
                                    finish()
                                }
                            },
                    liveRoom.speakQueueVM.observableOfMixModePresenterChange
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                finish()
                            },
                    //fix房间里播放了老师声音
                    //join room之后关闭远端音频
                    liveRoom.speakQueueVM.observableOfWebrtcMode
                            .filter {  it }
                            .delay(1,TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                liveRoom.player.muteAllRemoteAudio(true)
                            },

                    liveRoom.getRecorder<LPRecorder>().observableOfCameraOn
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            setDefinitionText(recorder?.videoDefinition)
                        }
            )
        }
        disposeOfAutoHide = Observable.interval(1L, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    noTouchTime++
                    if (showMenu && noTouchTime >= AUTO_HIDE_TIME) {
                        showMenu(false)
                    }
                }
        liveRoom.speakQueueVM.requestActiveUsers()
    }

    private fun showStopAsCamera() {
        finish()
    }

    private fun showMenu(show: Boolean) {
        this.showMenu = show
        menuContainer.visibility = if (show) View.VISIBLE else View.GONE
    }

    private fun initEvent() {
        videoContainer.setOnTouchListener { v, _ ->
            showMenu(true)
            noTouchTime = 0
            v.performClick()
        }
    }

    override fun finish() {
        if (roomExitListener != null) {
            roomExitListener!!.onRoomExit(this, object : LiveCameraWithUI.LPRoomExitCallback {
                override fun exit() {
                    super@AsCameraActivity.finish()
                }

                override fun cancel() {
                    // do nothing
                }
            })
        } else {
            super.finish()
        }
    }

    private fun showMessage(message: String) {
        showToastMessage(message)
    }

    private fun initLiveRoom() {
        liveRoom?.run {
            setOnLiveRoomListener { error ->
                when (error.code.toInt()) {
                    LPError.CODE_ERROR_ROOMSERVER_LOSE_CONNECTION,
                    LPError.CODE_ERROR_WEBRTC_SERVER_DISCONNECTED -> reEnterRoom(LiveSDK.checkTeacherUnique, false)
                    LPError.CODE_ERROR_NETWORK_FAILURE -> showMessage(error.message)
                    LPError.CODE_ERROR_NETWORK_MOBILE -> {
                        val isForeground = CommonUtils.isAppForeground(this@AsCameraActivity)
                        if (!mobileNetworkDialogShown && isForeground) {
                            mobileNetworkDialogShown = true
                            try {
                                if (isFinishing) return@setOnLiveRoomListener
                                MaterialDialog.Builder(this@AsCameraActivity)
                                        .content(getString(R.string.base_live_mobile_network_hint))
                                        .positiveText(getString(R.string.base_live_mobile_network_confirm))
                                        .positiveColor(ContextCompat.getColor(this@AsCameraActivity, R.color.base_theme_live_product))
                                        .onPositive { materialDialog, _ -> materialDialog.dismiss() }
                                        .canceledOnTouchOutside(true)
                                        .build()
                                        .show()
                            } catch (e: WindowManager.BadTokenException) {
                                e.printStackTrace()
                            }
                        } else {
                            showMessage(getString(R.string.base_live_mobile_network_hint_less))
                        }
                    }
                    LPError.CODE_ERROR_LOGIN_CONFLICT -> {
                        // do nothing
                    }
                    LPError.CODE_ERROR_OPEN_AUDIO_RECORD_FAILED, LPError.CODE_ERROR_OPEN_AUDIO_CAMERA_FAILED -> {
                        if (!TextUtils.isEmpty(error.message)) {
                            showMessage(error.message)
                        }
                    }
                    LPError.CODE_WARNING_PLAYER_LAG, LPError.CODE_WARNING_PLAYER_MEDIA_SUBSCRIBE_TIME_OUT,
                    LPError.CODE_ERROR_MEDIA_PLAY_FAILED -> {
                        // do nothing
                    }
                    else -> if (!TextUtils.isEmpty(error.message)) {
                        showMessage(error.message)
                    }
                }
            }
        }
    }

    private fun release(quitRoom: Boolean = false) {
        enterRoomSuccess = false
        LPRxUtils.dispose(disposes)
        LPRxUtils.dispose(disposeOfAutoHide)
        removeAllFragment()
        if (quitRoom) {
            liveRoom?.quitRoom()
        }
    }

    private fun checkCameraPermission(): Boolean {
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
            return true
        } else {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_PERMISSION_CAMERA)
        }
        return false
    }

    private fun showPlaceholder(showPlaceholder: Boolean) {
        ivPlaceholder.visibility = if (showPlaceholder) View.VISIBLE else View.GONE
        tvPlaceholder.visibility = if (showPlaceholder) View.VISIBLE else View.GONE
        cameraView.visibility = if (!showPlaceholder) View.VISIBLE else View.GONE
    }

    private fun attachLocalVideo() {
        if (checkCameraPermission()) {
            recorder?.run {
                this@AsCameraActivity.cameraView.aspectRatio = LPConstants.LPAspectRatio.Fill
                setPreview(this@AsCameraActivity.cameraView)
                if (!isPublishing) {
                    publish()
                }
                attachVideo()
                showPlaceholder(false)
            }
        }
    }

    /**
     * isScreenShare ,true屏幕分享，false 是播放视频
     */
    private fun detechLocalVideo(isScreenShare: Boolean? = null) {
        showPlaceholder(true)
        recorder?.stopPublishing()
        when (isScreenShare) {
            true -> {
                ivPlaceholder.setImageResource(R.drawable.base_ic_video_default_head)
                tvPlaceholder.text = getString(R.string.base_live_ascamera_screen_share)
            }
            false -> {
                ivPlaceholder.setImageResource(R.drawable.base_ic_video_default_head)
                tvPlaceholder.text = getString(R.string.base_live_ascamera_media)
            }
            else -> {
                ivPlaceholder.setImageResource(R.drawable.base_ic_video_camera_mute)
                tvPlaceholder.visibility = View.GONE
            }
        }
    }


    /**
     * 重进房间或者重连
     * reEnterRoom： true重进 false重连
     */
    private fun doReEnterRoom(checkTeacherUnique: Boolean, reEnterRoom: Boolean = false) {
        LiveSDK.checkTeacherUnique = checkTeacherUnique
        if (reEnterRoom) {
            isReconnect = false
            release(true)
            enterRoom()
        } else {
            isReconnect = true
            release()
            enterRoom(liveRoom)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        release(true)
        menuDialog?.dismiss()
    }

    override fun getShowTechSupport() = showTechSupport

    override fun setShowTechSupport(showTechSupport: Boolean) {
        this.showTechSupport = showTechSupport
    }

    override fun getErrorSuggestion(): String? = liveRoom?.partnerConfig?.customerDefaultExceptionMessage

    override fun reEnterRoom(checkUnique: Boolean, isReEnter: Boolean) {
        doReEnterRoom(checkUnique, isReEnter)
    }

    override fun isReconnect() = isReconnect

    override fun dismissErrorDlg() {
        removeFragment(errorFragment)
    }

    override fun showError(lpError: LPError?) {
        lpError?.let {
            when (it.code) {
                LPError.CODE_ERROR_LOGIN_KICK_OUT.toLong() -> showKickOutDlg(it) //被踢出房间后的登录
                else -> {
                    hideLoading(loadingWindow?.view)
                    if (errorFragment.isAdded) return
                    showErrorDlg(it)
                }
            }
        }
    }

    private fun showSystemSettingDialog() {
        MaterialDialog.Builder(this)
                .title(getString(R.string.base_live_sweet_hint))
                .content(getString(R.string.base_live_no_camera_permission))
                .positiveText(getString(R.string.base_live_confirm))
                .positiveColor(ContextCompat.getColor(this, R.color.base_theme_live_product))
                .onPositive { dialog: MaterialDialog, which: DialogAction? -> dialog.dismiss() }
                .canceledOnTouchOutside(true)
                .build()
                .show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CODE_PERMISSION_CAMERA -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                attachLocalVideo()
                liveRoom?.onlineUserVM?.updateMediaState(LPConstants.MediaState.Normal,LPConstants.MediaState.Normal)
            } else if (grantResults.isNotEmpty()) {
                showSystemSettingDialog()
                liveRoom?.onlineUserVM?.updateMediaState(LPConstants.MediaState.Normal,LPConstants.MediaState.PermissionDeny)
            }
            else -> {
                // do nothing
            }
        }
    }
}